package com.stylefeng.guns.modular.huamao.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.stylefeng.guns.modular.huamao.common.GetOrderNum;
import com.stylefeng.guns.modular.huamao.dao.*;
import com.stylefeng.guns.modular.huamao.model.*;
import com.stylefeng.guns.modular.huamao.result.AppResult;
import com.stylefeng.guns.modular.huamao.service.IAppAccountService;
import com.stylefeng.guns.modular.huamao.service.ISktHuamaobtLogService;
import com.stylefeng.guns.modular.huamao.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class AppAccountServiceImpl extends ServiceImpl<AccountMapper, Account> implements IAppAccountService {
    @Autowired
    private AccountMapper accountMapper;
    @Autowired
    private UsersDrawsMapper usersDrawsMapper;
    @Autowired
    private UsersRechargeMapper usersRechargeMapper;
    @Autowired
    private SktShopsMapper sktShopsMapper;
    @Autowired
    private SktSysConfigsMapper sysConfigsMapper;
    @Autowired
    private AccountShopMapper accountShopMapper;
    @Autowired
    private SktOrdersStockscoreMapper sktOrdersStockscoreMapper;

    @Override
    public List<UsersDraws> presentProgress(Map<String, Object> map) {

        return usersDrawsMapper.presentProgress(map);
    }

    @Override
    public MyAccountHuabao myHuaBao(Integer userId) {
        return accountMapper.myHuaBao(userId);
    }

    @Override
    public Account selectAccountByUserId(Integer userId) {
        return accountMapper.selectAccountByuserId(userId);
    }

    @Override
    public Account scoreIndex(Integer userId) {
        return accountMapper.scoreIndex(userId);
    }

    //用户充值生成订单
    @Override
    public JSONObject recharge(Integer userId, int payType, BigDecimal cash, String remark, Integer status) {
        JSONObject json = new JSONObject();
        //用户充值记录
        UsersRecharge recharge = new UsersRecharge();
        // 生成订单号
        SimpleDateFormat sfDate = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String strDate = sfDate.format(new Date());
        String num = GetOrderNum.getRandom620(2);
        recharge.setOrderNo("7" + strDate + num);
        recharge.setUserId(userId);
        recharge.setPayType(payType);
        recharge.setCash(cash);
        recharge.setRemark(remark);
        recharge.setStatus(status);
        recharge.setCreateTime(new Date());
        Integer insert = usersRechargeMapper.insert(recharge);
        json.put("code", "01");
        /**
         * 支付方式 1:线下现金支付 2 现金账户支付
         * 3开元宝支付 4第三方支付 5混合支付 6开元宝营业额
         */

        json.put("orderNO", recharge.getOrderNo());
        json.put("cash", cash);
        json.put("type", "RECHARGE");
        json.put("allowPayType", "1,4");
        json.put("orderId", recharge.getId());
        json.put("msg", "下单成功！");
        return json;
    }

    @Override
    public AppResult isBuyAPPTimeScore(Integer shopId, BigDecimal cash) {
        Map<String, Object> json = new HashMap<>();
        //查询购买赠送比例
        SktSysConfigs buyStockScore = sysConfigsMapper.selectSysConfigsByFieldCode("buyStockScorePrice");
        //查询申请库存积分开始时间
        SktSysConfigs beginTime = sysConfigsMapper.selectSysConfigsByFieldCode("buyStockScoreStart");
        // 查询申请结束时间
        SktSysConfigs endTime = sysConfigsMapper.selectSysConfigsByFieldCode("buyStockScoreEnd");
        //查询当前时间并转换成相应格式
        SimpleDateFormat sfDate = new SimpleDateFormat("HHmmss");
        String strDate = sfDate.format(new Date());
        int date = Integer.parseInt(strDate);
        int end = Integer.parseInt(endTime.getFieldValue());
        //传来的end为小时，没显示分、秒，加上为了和现在时间做比较
        String end2 = end + "0000";
        end = Integer.parseInt(end2);
        int begin = Integer.parseInt(beginTime.getFieldValue());
        //传来的begin为小时，没显示分、秒，加上为了和现在时间做比较
        String begin2 = begin + "0000";
        begin = Integer.parseInt(begin2);
        //判断是否在允许购买时间段内
        if (date <= end && date >= begin) {
            //如果在的话，就查询账户余额
            SktShops sktShops = sktShopsMapper.selectById(shopId);
            Integer userId = sktShops.getUserId();
            AccountShopDTO accountShopDTO = accountShopMapper.findAccountByUserId(userId);
            // 生成订单号
            String orderNo= StringUtils.getOrderIdByTime("a");
            //生成购买库存积分记录
            Integer insert = this.buyAppStockScore(accountShopDTO.getUserId(), 4, cash, new BigDecimal(0),
                    new BigDecimal(0), new BigDecimal(0), new BigDecimal(0), cash.divide(new BigDecimal(Integer.parseInt(buyStockScore.getFieldValue())), 6, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(10000)), "商家下单申请积分",orderNo);
            //现金余额
            json.put("cash", accountShopDTO.getCash());
            //华宝余额
            json.put("kaiyuan", accountShopDTO.getKaiyuan());
            //华宝货款余额
            json.put("kaiyuanTurnover", accountShopDTO.getKaiyuanTurnover());
            //查询华宝支付手续费
            SktSysConfigs kaiyuanFee = sysConfigsMapper.selectSysConfigsByFieldCode("kaiyuanFee");
            accountShopDTO.setKaiyuanFee(new BigDecimal(kaiyuanFee.getFieldValue()).divide(new BigDecimal(100)).multiply(cash));
            //综合服务费
            SktSysConfigs taxRatio = sysConfigsMapper.selectSysConfigsByFieldCode("taxRatio");
            //传入json华宝支付服务费
            json.put("hbFee", new BigDecimal(taxRatio.getFieldValue()).add(new BigDecimal(kaiyuanFee.getFieldValue())).divide(new BigDecimal(100)).multiply(cash));//华宝支付所需总费用
            //华宝货款手续费
            SktSysConfigs kaiyuanturnFee = sysConfigsMapper.selectSysConfigsByFieldCode("kaiyuanturnFee");
            //华宝货款支付所需服务费
            json.put("huabaoturnFee", new BigDecimal(kaiyuanturnFee.getFieldValue()).divide(new BigDecimal(100)).multiply(cash));
            /**
             * 支付方式 1:线下现金支付 2 现金账户支付
             * 3开元宝支付 4第三方支付 5混合支付 6开元宝营业额
             */
            if (insert == 1) {
                json.put("allowPayType", "2,3,4,6");
                json.put("orderNo",orderNo);
                return AppResult.OK("下单成功！",json);
            }
            return AppResult.ERROR("操作失败",-1);
        }
        return AppResult.ERROR("购买库存积分请在" + beginTime.getFieldValue() + "点到" + endTime.getFieldValue() + "点之间！",-1);
    }

    @Override
    public Map<String, Object> selectAccountAndAccountShopByUserId(Integer userId) {
        return accountMapper.selectAccountAndAccountShopByUserId(userId);
    }

    @Override
    public boolean updateAccountById(Account account) {
        int i=accountMapper.updateAccountById(account);
        if (i>0){
            return true;
        }
        return false;
    }

    //购买库存积分记录
    @Transactional
    public Integer buyAppStockScore(Integer userId, Integer payType, BigDecimal totalMoney, BigDecimal realMoney,
                                 BigDecimal cash, BigDecimal kaiyuan, BigDecimal kaiyuanFee, BigDecimal score, String orderRemarks,String orderNo) {
        SktOrdersStockscore sktOrdersStockscore = new SktOrdersStockscore();
        sktOrdersStockscore.setOrderNo(orderNo);
        sktOrdersStockscore.setUserId(userId);
        sktOrdersStockscore.setPayType(payType);
        sktOrdersStockscore.setTotalMoney(totalMoney);
        sktOrdersStockscore.setRealMoney(realMoney);
        sktOrdersStockscore.setCash(cash);
        sktOrdersStockscore.setKaiyuan(kaiyuan);
        sktOrdersStockscore.setKaiyuanFee(kaiyuanFee);
        sktOrdersStockscore.setScore(score);
        sktOrdersStockscore.setOrderRemarks(orderRemarks);
        sktOrdersStockscore.setCreateTime(new Date());
        Integer insert = sktOrdersStockscoreMapper.insert(sktOrdersStockscore);
        return insert;
    }

}
